const db=require('../db/index.js')
// 数据库查询工具函数
const queryDb = (sql, params) => {
  return new Promise((resolve, reject) => {
    db.query(sql, params, (err, result) => {
      if (err) reject(err); // 出错时 reject
      else resolve(result); // 成功时 resolve 结果
    });
  });
};
//得到热门问题列表接口
const getHotQuestions = async (req, res) => {
  try {
    // 1. 固定参数配置（无需前端传递）
    const tag = '全部'; // tag固定为全部
    const limitNum = 5; // 取前5条
    const offset = 0; // 固定第一页

    // 2. 构建查询条件（保持不变）
    let whereConditions = [
      "q.status = 1", // 仅查询正常状态的问题
      "q.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
    ];
    let queryParams = [];
    let filterDesc = `标签「${tag}」+七天内`;

    // 关键词搜索（保留可选功能）
    const { keyword } = req.query;
    if (keyword && keyword.trim() !== '') {
      whereConditions.push("(q.title LIKE ? OR q.content LIKE ?)");
      const keywordTrim = keyword.trim();
      queryParams.push(`%${keywordTrim}%`, `%${keywordTrim}%`);
      filterDesc += `+关键词「${keywordTrim}」`;
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : "";

    // 3. 查询热门问题（移除 q.like_count、q.dislike_count 字段）
    const hotQuestionsSql = `
      SELECT 
        q.id,
        q.title,
        q.content,
        q.tags,
        q.view_count,
        q.answer_count,
        q.collect_count,
        q.hot_score,
        q.created_at,
        u.id as asker_id,
        u.nickname as asker_name,
        u.avatar as asker_avatar
      FROM questions q
      LEFT JOIN users u ON q.asker_id = u.id
      ${whereClause}
      ORDER BY q.hot_score DESC, q.created_at DESC
      LIMIT ? OFFSET ?
    `;

    // 执行查询（参数逻辑不变）
    const questionsResult = await queryDb(hotQuestionsSql, [...queryParams, limitNum, offset]);

    // 4. 查询总数量（保持不变）
    const countSql = `
      SELECT COUNT(*) as total
      FROM questions q
      ${whereClause}
    `;
    const countResult = await queryDb(countSql, queryParams);
    const total = countResult[0].total;

    // 5. 格式化返回数据（移除 likeCount 字段）
    const hotQuestions = questionsResult.map(question => ({
      id: question.id,
      title: question.title,
      content: question.content,
      tags: question.tags ? question.tags.split(',') : [],
      viewCount: question.view_count,
      answerCount: question.answer_count,
      collectCount: question.collect_count, // 保留：问题收藏数
      hotScore: question.hot_score || 0,    // 保留：问题热度值
      createdAt: question.created_at,
      asker: {
        id: question.asker_id,
        nickname: question.asker_name || '匿名用户',
        avatar: question.asker_avatar || '默认头像地址',
      }
    }));

    // 5.1 时间格式处理（保持不变）
    hotQuestions.forEach(q => {
      if (q.createdAt) {
        const date = new Date(q.createdAt);
        q.createdAt = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
      }
    });

    // 6. 响应数据（保持不变）
    const responseData = {
      status: 200,
      message: total > 0 
        ? `获取一天内热门前十条问题成功（共${total}条符合条件）` 
        : `暂无${filterDesc}的热门问题`,
      data: {
        hotQuestions,
        pagination: {
          page: 1,
          limit: 10,
          total,
          totalPages: Math.ceil(total / 10) || 0
        },
        currentFilter: {
          tag: '全部',
          timeRange: '1天内',
          keyword: keyword || ''
        }
      }
    };

    return res.status(200).json(responseData);

  } catch (err) {
    console.error("获取一天内热门前十条问题异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "获取一天内热门前十条问题失败：服务器内部错误",
      error: process.env.NODE_ENV === 'development' ? err.message : undefined,
    });
  }
};
// 获取问题列表接口（含空数据说明版）
const getQuestions = async (req, res) => {
  try {
    // 1. 参数校验
    const { page = 1, limit = 10, tag, keyword } = req.query;
    const pageNum = Number(page);
    const limitNum = Number(limit);
    if (isNaN(pageNum) || pageNum < 1 || isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：页码和每页数量必须为正整数，且每页数量不能超过100"
      });
    }
    if (!tag && !keyword) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：至少需要提供一个标签或关键词进行搜索"
      });
    }
    const validTags = ['全部', '计算机类', '英语类', '数学类', '物理类', '通识类'];
    if (tag && !validTags.includes(tag)) {
      return res.status(400).json({
        status: 400,
        message: `参数错误：标签必须是以下选项之一：${validTags.join('、')}`
      });
    }

    const offset = (pageNum - 1) * limitNum;

    // 2. 构建查询条件和参数
    let whereConditions = ["q.status = 1"];
    let queryParams = [];
    let filterDesc = "正常状态";
    if (tag && tag !== '全部') {
      whereConditions.push("FIND_IN_SET(?, q.tags)");
      queryParams.push(tag);
      filterDesc = `标签「${tag}」`;
    }
    if (keyword && keyword.trim() !== '') {
      whereConditions.push("(q.title LIKE ? OR q.content LIKE ?)");
      const keywordTrim = keyword.trim();
      queryParams.push(`%${keywordTrim}%`, `%${keywordTrim}%`);
      filterDesc += `+关键词「${keywordTrim}」`;
    }
    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : "";

    // 3. 查询问题列表（删除 q.like_count 字段）
    const questionsSql = `
      SELECT 
        q.id,
        q.title,
        q.content,
        q.tags,
        q.view_count,
        q.answer_count,
        q.created_at,
        u.id as asker_id,
        u.nickname as asker_name,
        u.avatar as asker_avatar
      FROM questions q
      LEFT JOIN users u ON q.asker_id = u.id
      ${whereClause}
      ORDER BY q.created_at DESC
      LIMIT ? OFFSET ?
    `;

    const questionsResult = await queryDb(questionsSql, [...queryParams, limitNum, offset]);

    // 4. 查询总数量（保持不变）
    const countSql = `
      SELECT COUNT(*) as total
      FROM questions q
      ${whereClause}
    `;
    const countResult = await queryDb(countSql, queryParams);
    const total = countResult[0].total;

    // 5. 格式化返回数据
    const questions = questionsResult.map(question => ({
      id: question.id,
      title: question.title,
      content: question.content,
      tags: question.tags ? question.tags.split(',') : [],
      viewCount: question.view_count,
      answerCount: question.answer_count,
      createdAt: question.created_at,
      asker: {
        id: question.asker_id,
        nickname: question.asker_name || '匿名用户',
        avatar: question.asker_avatar || '默认头像地址',
      }
    }));
    // 5.1 时间格式处理
    questions.forEach(q => {
      if (q.createdAt) {
        const date = new Date(q.createdAt);
        q.createdAt = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
      }
    });

    // 6. 响应数据
    const responseData = {
      status: 200,
      message: total > 0 
        ? "获取问题列表成功" 
        : `暂无符合${filterDesc}的问题，可尝试调整筛选条件或关键词`,
      data: {
        questions,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          totalPages: Math.ceil(total / limitNum) || 0,
        },
        availableTags: validTags,
        currentFilter: {
          tag: tag || '全部',
          keyword: keyword || '',
        }
      }
    };

    return res.status(200).json(responseData);

  } catch (err) {
    console.error("获取问题列表异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "获取问题列表失败：服务器内部错误",
      error: process.env.NODE_ENV === 'development' ? err.message : undefined,
    });
  }
};

// 获取问题详情接口
const getQuestionDetail = async (req, res) => {
  try {
    // 参数校验
    const { id } = req.query;
    const questionId = Number(id);

    if (!questionId || isNaN(questionId)) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：问题ID不能为空且必须为数字"
      });
    }

    // 查询问题详情
    const questionSql = `
      SELECT 
        q.id,
        q.title,
        q.content,
        q.tags,
        q.view_count,
        q.answer_count,
        q.collect_count,  
        q.hot_score,      
        q.created_at,
        q.updated_at,
        u.id as asker_id,
        u.nickname as asker_name,
        u.avatar as asker_avatar
      FROM questions q
      LEFT JOIN users u ON q.asker_id = u.id
      WHERE q.id = ? AND q.status = 1
      LIMIT 1
    `;

    const questionResult = await queryDb(questionSql, [questionId]);

    // 处理问题不存在的情况
    if (questionResult.length === 0) {
      return res.status(404).json({
        status: 404,
        message: "问题不存在或已被删除"
      });
    }

    // 更新浏览数
    const updateViewSql = `
      UPDATE questions 
      SET view_count = view_count + 1 
      WHERE id = ?
    `;
    await queryDb(updateViewSql, [questionId]);

    // 查询问题的回答
    const answersSql = `
      SELECT 
        a.id,
        a.content,
        a.like_count,
        a.dislike_count,   
        a.hot_score,    
        a.created_at,
        u.id as author_id,
        u.nickname as author_name,
        u.avatar as author_avatar
      FROM answers a
      LEFT JOIN users u ON a.author_id = u.id
      WHERE a.question_id = ? AND a.status = 1
      ORDER BY a.hot_score DESC, a.like_count DESC, a.created_at ASC
    `;

    const answersResult = await queryDb(answersSql, [questionId]);

    // 6. 格式化返回数据
    const question = {
      id: questionResult[0].id,
      title: questionResult[0].title,
      content: questionResult[0].content,
      tags: questionResult[0].tags ? questionResult[0].tags.split(',') : [],
      viewCount: questionResult[0].view_count + 1, 
      answerCount: questionResult[0].answer_count,
      collectCount: questionResult[0].collect_count, 
      hotScore: questionResult[0].hot_score,       
      createdAt: questionResult[0].created_at,
      updatedAt: questionResult[0].updated_at,
      asker: {
        id: questionResult[0].asker_id,
        username: questionResult[0].asker_name,
        avatar: questionResult[0].asker_avatar
      },
      answers: answersResult.map(answer => ({
        id: answer.id,
        content: answer.content,
        likeCount: answer.like_count,       
        dislikeCount: answer.dislike_count, 
        hotScore: answer.hot_score, 
        createdAt: answer.created_at,
        author: {
          id: answer.author_id,
          username: answer.author_name,
          avatar: answer.author_avatar
        }
      }))
    };

    // 7. 返回成功响应（保持不变）
    return res.status(200).json({
      status: 200,
      message: "获取问题详情成功",
      data: question
    });

  } catch (err) {
    // 8. 错误处理（保持不变）
    console.error("获取问题详情异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "获取问题详情失败：服务器内部错误",
      error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
  }
};
// 提交回答接口
const submitAnswer = async (req, res) => {
  try {
    // 1. 接收前端参数（与前端提交逻辑对应）
    const { questionId, content, authorId } = req.body;

    // 2. 必传参数验证
    if (!questionId || !content.trim() || !authorId) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：问题ID、回答内容、回答者ID不能为空",
        data: null
      });
    }

    // 3. 步骤1：插入回答到answers表（新增hot_score初始化，默认0）
    const insertAnswerSql = `
      INSERT INTO answers (question_id, content, author_id, hot_score)
      VALUES (?, ?, ?, 0)
    `;
    const insertResult = await queryDb(insertAnswerSql, [questionId, content.trim(), authorId]);

    // 4. 步骤2：查询当前问题的统计数据（用于计算新热度）
    const getQuestionSql = `
      SELECT view_count, answer_count, collect_count
      FROM questions
      WHERE id = ? AND status = 1
      LIMIT 1
    `;
    const questionResult = await queryDb(getQuestionSql, [questionId]);
    if (questionResult.length === 0) {
      return res.status(404).json({
        status: 404,
        message: "目标问题不存在或已删除",
        data: null
      });
    }
    const { view_count, answer_count, collect_count } = questionResult[0];

    // 5. 步骤3：更新questions表的answer_count和hot_score
    const newAnswerCount = answer_count + 1;
    // 按表结构定义的热度公式计算：浏览数×0.1 + 回答数×5 + 点赞数×2 + 收藏数×3 - 踩数×3
    const newHotScore = Math.round(
      view_count * 0.1 + newAnswerCount * 5 + (collect_count || 0) * 3
    );

    const updateQuestionSql = `
      UPDATE questions
      SET answer_count = ?, hot_score = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    await queryDb(updateQuestionSql, [newAnswerCount, newHotScore, questionId]);

    // 6. 步骤4：查询新创建的回答完整信息（含作者信息，新增hot_score字段）
    const getNewAnswerSql = `
      SELECT 
        a.id,
        a.question_id,
        a.content,
        a.like_count,
        a.dislike_count,
        a.hot_score,
        a.created_at,
        u.nickname as author_name,
        u.avatar as author_avatar
      FROM answers a
      LEFT JOIN users u ON a.author_id = u.id
      WHERE a.id = ?
      LIMIT 1
    `;
    const newAnswerResult = await queryDb(getNewAnswerSql, [insertResult.insertId]);
    const newAnswer = newAnswerResult[0];

    // 7. 格式化返回数据（与前端渲染字段对应，新增hotScore）
    const formattedAnswer = {
      id: newAnswer.id,
      questionId: newAnswer.question_id,
      content: newAnswer.content,
      author: {
        id: authorId,
        username: newAnswer.author_name || "匿名用户",
        avatar: newAnswer.author_avatar || "https://picsum.photos/id/64/36/36" // 默认头像
      },
      likeCount: newAnswer.like_count || 0,
      dislikeCount: newAnswer.dislike_count || 0,
      hotScore: newAnswer.hot_score || 0, // 新增返回热度值
      createdAt: newAnswer.created_at 
        ? new Date(newAnswer.created_at).toISOString() 
        : new Date().toISOString()
    };

    // 8. 响应成功结果
    return res.status(200).json({
      status: 200,
      message: "回答提交成功",
      data: {
        answer: formattedAnswer,
        updatedQuestion: {
          answerCount: newAnswerCount,
          hotScore: newHotScore
        }
      }
    });

  } catch (err) {
    console.error("提交回答异常:", err.stack);
    // 捕获外键约束错误（比如author_id不存在、question_id无效）
    let errorMsg = "服务器内部错误，提交失败";
    if (err.code === "ER_NO_REFERENCED_ROW_2") {
      errorMsg = "关联数据无效：回答者ID或问题ID不存在";
    }
    res.status(500).json({
      status: 500,
      message: errorMsg,
      error: process.env.NODE_ENV === 'development' ? err.message : undefined,
      data: null
    });
  }
};

// 回答点赞接口
const likeAnswer = async (req, res) => {
  try {
    const { answerId, userId } = req.body;

    if (!answerId || !userId) {
      return res.status(400).json({ status: 400, message: "参数错误：回答ID和用户ID不能为空", data: null });
    }

    // 查询时新增
    const getAnswerSql = `
      SELECT a.id, a.question_id, a.like_count, a.dislike_count, q.view_count, q.answer_count, q.collect_count
      FROM answers a LEFT JOIN questions q ON a.question_id = q.id
      WHERE a.id = ? AND a.status = 1 AND q.status = 1 LIMIT 1
    `;
    const answerResult = await queryDb(getAnswerSql, [answerId]);
    if (answerResult.length === 0) {
      return res.status(404).json({ status: 404, message: "目标回答不存在或已删除", data: null });
    }
    // 解构时新增dislike_count
    const { question_id: questionId, like_count: currentLikeCount, dislike_count: currentDislikeCount, view_count, answer_count, collect_count } = answerResult[0];

    // 检查当前点赞状态
    const checkOpSql = `
      SELECT id, status FROM user_answer_operations
      WHERE user_id = ? AND answer_id = ? AND operation_type = 1 LIMIT 1
    `;
    const opResult = await queryDb(checkOpSql, [userId, answerId]);
    const isLiked = opResult.length > 0 && opResult[0].status === 1;

    // 计算新点赞数
    const newLikeCount = isLiked ? Math.max(0, currentLikeCount - 1) : currentLikeCount + 1;

    try {
      // 更新点赞数 + 同步更新回答热度（公式：点赞×3 - 踩×2，兼容NULL）
      await queryDb(`
        UPDATE answers 
        SET 
          like_count = ?,
          hot_score = ROUND(IFNULL(like_count, 0) * 3 - IFNULL(dislike_count, 0) * 2),
          updated_at = CURRENT_TIMESTAMP 
        WHERE id = ?
      `, [newLikeCount, answerId]);
      // 原逻辑：更新点赞数

      // 新增：查询更新后的回答最新热度
      const getAnswerHotScoreSql = `
        SELECT hot_score FROM answers 
        WHERE id = ? AND status = 1 
        LIMIT 1
      `;
      const hotScoreResult = await queryDb(getAnswerHotScoreSql, [answerId]);
      // 兼容hot_score为NULL的情况，默认返回0
      const answerNewHotScore = hotScoreResult[0]?.hot_score || 0;
      
      // 更新/插入操作记录
      if (opResult.length > 0) {
        await queryDb(`UPDATE user_answer_operations SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [isLiked ? 0 : 1, opResult[0].id]);
      } else {
        await queryDb(`INSERT INTO user_answer_operations (user_id, answer_id, operation_type, status) VALUES (?, ?, 1, 1)`, [userId, answerId]);
      }

      // 同步问题热度
      const newHotScore = Math.round(
        view_count * 0.1 + answer_count * 5 + newLikeCount * 2 + (collect_count || 0) * 3
      );
      await queryDb(`UPDATE questions SET hot_score = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [newHotScore, questionId]);

      return res.status(200).json({
        status: 200,
        message: isLiked ? "取消点赞成功" : "点赞成功",
        data: { 
          answerId, 
          newLikeCount, 
          isLiked: !isLiked,
          answerNewHotScore // 新增：返回改变后的回答热度
        }
      });

    } catch (updateErr) {
      console.error("操作失败:", updateErr.stack);
      return res.status(500).json({ status: 500, message: "操作失败：服务器内部错误", data: null });
    }

  } catch (err) {
    console.error("接口异常:", err.stack);
    res.status(500).json({ status: 500, message: "操作失败：服务器内部错误", data: null });
  }
};

// 回答踩接口
const dislikeAnswer = async (req, res) => {
  try {
    const { answerId, userId } = req.body;

    // 1. 必传参数校验
    if (!answerId || !userId) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：回答ID和用户ID不能为空",
        data: null
      });
    }

    // 2. 校验回答+关联问题：新增a.like_count（用于计算热度）
    const getAnswerSql = `
      SELECT a.id, a.question_id, a.dislike_count, a.like_count, q.view_count, q.answer_count, q.collect_count
      FROM answers a
      LEFT JOIN questions q ON a.question_id = q.id
      WHERE a.id = ? AND a.status = 1 AND q.status = 1
      LIMIT 1
    `;
    const answerResult = await queryDb(getAnswerSql, [answerId]);
    if (answerResult.length === 0) {
      return res.status(404).json({
        status: 404,
        message: "目标回答不存在或已删除",
        data: null
      });
    }
    // 解构：新增like_count
    const { 
      question_id: questionId, 
      dislike_count: currentDislikeCount,
      like_count: currentLikeCount,
      view_count, answer_count, collect_count
    } = answerResult[0];

    // 3. 判断当前踩状态
    const checkOpSql = `
      SELECT id, status FROM user_answer_operations
      WHERE user_id = ? AND answer_id = ? AND operation_type = 2
      LIMIT 1
    `;
    const opResult = await queryDb(checkOpSql, [userId, answerId]);
    const isDisliked = opResult.length > 0 && opResult[0].status === 1;

    // 4. 计算新踩数
    const newDislikeCount = isDisliked 
      ? Math.max(0, currentDislikeCount ? currentDislikeCount - 1 : 0) 
      : currentDislikeCount ? currentDislikeCount + 1 : 1;

    try {
      // 4.1 更新answers表踩数 + 同步更新回答热度（公式：点赞×3 - 踩×2，兼容NULL）
      await queryDb(`
        UPDATE answers 
        SET 
          dislike_count = ?,
          hot_score = ROUND(IFNULL(like_count, 0) * 3 - IFNULL(dislike_count, 0) * 2),
          updated_at = CURRENT_TIMESTAMP 
        WHERE id = ?
      `, [newDislikeCount, answerId]);

      // 新增：查询更新后的回答最新热度
      const getAnswerHotScoreSql = `
        SELECT hot_score FROM answers 
        WHERE id = ? AND status = 1 
        LIMIT 1
      `;
      const hotScoreResult = await queryDb(getAnswerHotScoreSql, [answerId]);
      // 兼容hot_score为NULL的情况，默认返回0
      const answerNewHotScore = hotScoreResult[0]?.hot_score || 0;

      // 4.2 更新/插入关联表记录
      if (opResult.length > 0) {
        await queryDb(`
          UPDATE user_answer_operations 
          SET status = ?, updated_at = CURRENT_TIMESTAMP 
          WHERE id = ?
        `, [isDisliked ? 0 : 1, opResult[0].id]);
      } else {
        await queryDb(`
          INSERT INTO user_answer_operations (user_id, answer_id, operation_type, status) 
          VALUES (?, ?, 2, 1)
        `, [userId, answerId]);
      }

      // 4.3 同步问题热度
      const newHotScore = Math.round(
        view_count * 0.1 + answer_count * 5 + (collect_count || 0) * 3 - newDislikeCount * 3
      );
      await queryDb(`
        UPDATE questions SET hot_score = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?
      `, [newHotScore, questionId]);

      // 5. 响应结果
      return res.status(200).json({
        status: 200,
        message: isDisliked ? "取消踩成功" : "踩成功",
        data: { 
          answerId, 
          newDislikeCount, 
          isDisliked: !isDisliked,
          answerNewHotScore // 新增：返回改变后的回答热度
        }
      });

    } catch (updateErr) {
      console.error("操作失败:", updateErr.stack);
      return res.status(500).json({ status: 500, message: "操作失败：服务器内部错误", data: null });
    }

  } catch (err) {
    console.error("回答踩异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "操作失败：服务器内部错误",
      data: null
    });
  }
};
//获得用户对问题点赞和踩的状态
const getUserAnswerOpStatus = async (req, res) => {
  try {
    const { questionId, userId } = req.body;
    console.log(req.body);
    // 1. 必传参数校验
    if (!questionId || !userId) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：问题ID和用户ID不能为空",
        data: null
      });
    }

    // 2. 第一步：查询该问题下的所有有效回答（不限回答者，只要状态正常）
    const getAnswersSql = `
      SELECT id FROM answers
      WHERE question_id = ? AND status = 1
    `;
    const questionAnswers = await queryDb(getAnswersSql, [questionId]);
    if (questionAnswers.length === 0) {
      return res.status(200).json({
        status: 200,
        message: "该问题下无有效回答",
        data: [] // 无回答返回空数组，前端直接兼容
      });
    }

    // 提取所有回答ID，用于批量查询用户操作状态（提升性能）
    const answerIds = questionAnswers.map(item => item.id);

    // 3. 第二步：批量查询当前用户对这些回答的点赞/踩记录
    const checkOpsSql = `
      SELECT answer_id, operation_type, status 
      FROM user_answer_operations
      WHERE user_id = ? AND answer_id IN (?)
    `;
    const opResults = await queryDb(checkOpsSql, [userId, answerIds]);

    // 4. 整理结果：给每个回答匹配对应的点赞/踩状态（默认未操作：false）
    const result = questionAnswers.map(answer => {
      const answerId = answer.id;
      // 筛选当前回答的所有操作记录
      const targetOps = opResults.filter(op => op.answer_id === answerId);

      return {
        answerId, // 回答ID（用于前端匹配对应回答）
        likeStatus: targetOps.some(op => op.operation_type === 1 && op.status === 1), // 已点赞？
        dislikeStatus: targetOps.some(op => op.operation_type === 2 && op.status === 1) // 已踩？
      };
    });

    // 5. 响应结果
    return res.status(200).json({
      status: 200,
      message: "查询成功",
      data: result
    });
  } catch (err) {
    console.error("获取问题下回答操作状态异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "操作失败：服务器内部错误",
      data: null
    });
  }
};
// 问题收藏接口（POST请求）
const collectQuestion = async (req, res) => {
  try {
    const { questionId, userId } = req.body;

    // 1. 必传参数校验
    if (!questionId || !userId) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：问题ID和用户ID不能为空",
        data: null
      });
    }

    // 2. 校验问题是否存在且正常
    const getQuestionSql = `
      SELECT id, collect_count, view_count, answer_count
      FROM questions
      WHERE id = ? AND status = 1
      LIMIT 1
    `;
    const questionResult = await queryDb(getQuestionSql, [questionId]);
    if (questionResult.length === 0) {
      return res.status(404).json({
        status: 404,
        message: "目标问题不存在或已删除",
        data: null
      });
    }
    const { 
      collect_count: currentCollectCount,
      view_count, answer_count
    } = questionResult[0];

    // 3. 查询用户对该问题的收藏记录
    const checkCollectionSql = `
      SELECT id, status FROM user_question_collections
      WHERE user_id = ? AND question_id = ?
      LIMIT 1
    `;
    const collectionResult = await queryDb(checkCollectionSql, [userId, questionId]);
    const hasRecord = collectionResult.length > 0;
    const isCollected = hasRecord && collectionResult[0].status === 1;

    // 4. 计算新收藏数（避免负数）
    const newCollectCount = isCollected 
      ? Math.max(0, currentCollectCount - 1) 
      : currentCollectCount + 1;

    try {
      // 5. 更新问题收藏数
      await queryDb(`
        UPDATE questions
        SET collect_count = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `, [newCollectCount, questionId]);

      // 6. 处理收藏记录
      if (hasRecord) {
        await queryDb(`
          UPDATE user_question_collections
          SET status = ?, updated_at = CURRENT_TIMESTAMP
          WHERE id = ?
        `, [isCollected ? 0 : 1, collectionResult[0].id]);
      } else {
        await queryDb(`
          INSERT INTO user_question_collections (user_id, question_id, status)
          VALUES (?, ?, 1)
        `, [userId, questionId]);
      }

      // 7. 同步更新问题热度
      const newHotScore = Math.round(
        view_count * 0.1 + answer_count * 5 + newCollectCount * 3
      );
      await queryDb(`
        UPDATE questions
        SET hot_score = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `, [newHotScore, questionId]);

      // 8. 响应结果
      return res.status(200).json({
        status: 200,
        message: isCollected ? "取消收藏问题成功" : "收藏问题成功",
        data: {
          questionId,
          newCollectCount,
          isCollected: !isCollected, // 返回最新状态，方便前端同步
          updatedQuestionHotScore: newHotScore
        }
      });

    } catch (updateErr) {
      console.error("收藏操作更新失败:", updateErr.stack);
      return res.status(500).json({
        status: 500,
        message: "操作失败：服务器内部错误",
        data: null
      });
    }

  } catch (err) {
    console.error("收藏问题接口异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "操作失败：服务器内部错误",
      error: process.env.NODE_ENV === 'development' ? err.message : undefined,
      data: null
    });
  }
};
//得到用户对问题的收藏状态
const getUserQuestionCollectStatus = async (req, res) => {
  try {
    const { userId, questionId } = req.body;

    // 1. 参数校验
    if (!userId || !questionId) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：用户ID和问题ID不能为空",
        data: null
      });
    }

    // 2. 查询收藏状态（适配新表，通过status判断）
    const checkStatusSql = `
      SELECT status FROM user_question_collections
      WHERE user_id = ? AND question_id = ?
      LIMIT 1
    `;
    const collectResult = await queryDb(checkStatusSql, [userId, questionId]);

    // 3. 状态判断：有记录且status=1→已收藏，否则未收藏
    const collectStatus = collectResult.length > 0 && collectResult[0].status === 1;

    // 4. 响应结果
    return res.status(200).json({
      status: 200,
      message: "查询收藏状态成功",
      data: {
        questionId,
        userId,
        collectStatus // true=已收藏，false=未收藏
      }
    });

  } catch (err) {
    console.error("查询问题收藏状态异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "查询失败：服务器内部错误",
      data: null
    });
  }
};
// 创建问题接口
const createQuestion = async (req, res) => {
  try {
    // 1. 参数校验
    const { title, content, tags, askerId } = req.body;

    if (!title || title.trim().length === 0) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：问题标题不能为空"
      });
    }

    if (!askerId || isNaN(Number(askerId))) {
      return res.status(400).json({
        status: 400,
        message: "参数错误：提问者ID不能为空且必须为数字"
      });
    }

    const targetAskerId = Number(askerId);

    // 2. 验证用户是否存在
    const userSql = `
      SELECT id FROM users WHERE id = ? LIMIT 1
    `;
    const userResult = await queryDb(userSql, [targetAskerId]);

    if (userResult.length === 0) {
      return res.status(400).json({
        status: 400,
        message: "用户不存在"
      });
    }

    // 3. 插入问题数据（新增hot_score字段，初始值0）
    const insertSql = `
      INSERT INTO questions (title, content, asker_id, tags, hot_score)
      VALUES (?, ?, ?, ?, 0)
    `;

    const tagString = Array.isArray(tags) ? tags.join(',') : tags;

    const insertResult = await queryDb(insertSql, [
      title.trim(),
      content ? content.trim() : null,
      targetAskerId,
      tagString
    ]);

    // 4. 返回成功响应（新增hotScore字段，返回初始热度0）
    return res.status(200).json({
      status: 200,
      message: "创建问题成功",
      data: {
        id: insertResult.insertId,
        title: title.trim(),
        askerId: targetAskerId,
        hotScore: 0, // 新增：返回初始热度值
        createdAt: new Date().toISOString()
      }
    });

  } catch (err) {
    // 5. 错误处理
    console.error("创建问题异常:", err.stack);
    res.status(500).json({
      status: 500,
      message: "创建问题失败：服务器内部错误",
      error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
  }
};

module.exports = {
  getQuestions,
  getHotQuestions,
  getQuestionDetail,
  submitAnswer,
  likeAnswer,
  dislikeAnswer,
  getUserAnswerOpStatus,
  collectQuestion,
  getUserQuestionCollectStatus,
  createQuestion
};